// pages/propertyClue/propertyClue.ts
import {
  getClueTypeListAPI,
  getClueStatListAPI,
  getClueStatAmountAPI,
} from "../../api/property";
import { reportGetDebtorListApi } from "../../api/debtor";
import { debtorPrice } from "../../utils/util";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    perPage: 10,
    total: 0,
    scrollTop: 0, // scrollView 滚动位置
    hasNextPage: true,
    searchInputClass: "",
    placeholderText: "搜索...",
    cur: {
      defaultValue: [],
      options: [],
      idName: "",
    },
    visible: false,
    // 更新时间
    utime: { value: "", label: "" },
    utimeValue: ["all"], // 值数组
    utimeOptions: [
      { label: "全部", value: "all" },
      { label: "近180天", value: "180" },
      { label: "近90天", value: "90" },
      { label: "近30天", value: "30" },
      { label: "近7天", value: "7" },
    ],
    // 线索类型
    ptypeEnsureFlag: false, // 线索类型下拉框点击确认后为true
    ptype: [], // 选项数组 [{value:"", label:""}]
    ptypeValue: ["all"], // 值数组
    ptypeOptions: [
      // {label:"债权人代位权", value:"1", typeName:"",type:"",  num: 999, checked: false},
    ] as any,
    // 线索类型分布
    companyId: null, // companyId 指的是 债务人id
    companyName: "",
    dateInfo: "",
    totalAmount: "",
    totalNum: "",
    swiperPages: [],
    typeItemTotal: 0, // 线索类型总个数
    companyOptions: [], // 申请通过的企业列表
    keyWords: "", //搜索企业关键字
    // searchDisabled: true,
    clueStatList: [], // 财产线索列表
    listLoading: false, // 财产线索加载
    typeLoading: false, // 线索类型加载
    clueFields: {
      // 债务人代位权
      sx_dw: [
        { name: "次债务人", key: "c_xm_c" },
        { name: "债务人", key: "c_xm_b" },
        { name: "立案时间", key: "d_sarq" },
        { name: "案号", key: "c_baah" },
        { name: "经办法院", key: "c_fymc" },
        { name: "结案时间", key: "d_jarq" },
        { name: "线索价值（万元）", key: "bc_amount", valueType: "amountWan" },
      ],
      // 司法涉诉未结案
      sx_wja: [
        { name: "案号", key: "c_ah" },
        { name: "案件类型", key: "type_name" },
        { name: "诉讼地位", key: "n_ssdw" },
        { name: "立案时间", key: "d_larq" },
        { name: "线索价值（万元）", key: "n_qsbdje", valueType: "amountWan" },
        { name: "案件进展", key: "n_ajjzjd", valueType: "status" },
      ],
      // 股权质押
      stock_zy: [
        { name: "出质人", key: "stk_pawn_czper" },
        { name: "质押标的企业", key: "stk_pawn_bdper" },
        { name: "质权人", key: "stk_pawn_zqper" },
        { name: "公示时间", key: "publicity_date" },
        {
          name: "股权出质数额（万元）",
          key: "stk_pawn_czamt",
          valueType: "amount",
        },
        { name: "状态", key: "stk_pawn_status", valueType: "status" },
      ],
      // 股权质权
      stock_zq: [
        { name: "出质人", key: "stk_pawn_czper" },
        { name: "质押标的企业", key: "stk_pawn_bdper" },
        { name: "质权人", key: "stk_pawn_zqper" },
        { name: "公示时间", key: "publicity_date" },
        {
          name: "股权出质数额（万元）",
          key: "stk_pawn_czamt",
          valueType: "amount",
        },
        { name: "状态", key: "stk_pawn_status", valueType: "status" },
      ],
      // 股权- 债务人子公司
      stock_zgs: [
        { name: "被投资公司", key: "name" },
        { name: "认缴出资额（万元）", key: "should_capi", valueType: "amount" },
      ],

      // 股权 - 股东未实缴
      stock_wsj: [
        { name: "股东", key: "stock_name" },
        { name: "实缴出资额（万元）", key: "real_capi", valueType: "amount" },
        { name: "认缴出资额（万元）", key: "should_capi", valueType: "amount" },
        { name: "实缴出资时间", key: "capi_date" },
        { name: "认缴出资时间", key: "shoud_date" },
        { name: "线索价值（万元）", key: "amount", valueType: "amount" },
      ],
      // 股权- 一人制
      stock_yrz: [
        { name: "股东", key: "stock_name" },
        {
          name: "实缴出资额（万元）",
          key: "real_capi",
          valueType: "amount_default",
        },
        {
          name: "认缴出资额（万元）",
          key: "should_capi",
          valueType: "amount_default",
        },
        { name: "实缴出资时间", key: "capi_date" },
        { name: "认缴出资时间", key: "shoud_date" },
        { name: "线索价值（万元）", key: "amount", valueType: "amount" },
      ],
      // 土地抵押权
      real_td: [
        { name: "土地抵押权人", key: "mortgage_name" },
        { name: "土地抵押人", key: "mortgagor_name" },
        { name: "登记时间", key: "on_board_start_time" },
        {
          name: "评估金额（万元）",
          key: "assessment_price",
          valueType: "amount",
        },
        {
          name: "线索价值（万元）",
          key: "mortgage_price",
          valueType: "amount",
        },
        { name: "行政区", key: "administrative_area" },
      ],
      // 土地抵押
      real_js: [
        { name: "土地抵押权人", key: "mortgage_name" },
        { name: "土地抵押人", key: "mortgagor_name" },
        { name: "土地抵押登记起始时间", key: "on_board_start_time" },
        { name: "抵押结束时间", key: "on_board_end_time" },
        {
          name: "评估金额（万元）",
          key: "assessment_price",
          valueType: "amount",
        },
        {
          name: "线索价值（万元）",
          key: "mortgage_price",
          valueType: "amount",
        },
      ],
      // 土地拍卖
      real_pm: [
        { name: "项目位置", key: "reg_area" },
        { name: "土地总面积（公顷）", key: "land_area" },
        {
          name: "线索价值（万元）",
          key: "turnover_price",
          valueType: "amount",
        },
      ],
      // 动产抵押/质押
      property_dy: [
        { name: "抵押人", key: "company_name" },
        { name: "抵押权人", key: "name" },
        { name: "登记时间", key: "register_date" },
        { name: "登记编号", key: "register_no" },
        {
          name: "线索价值（万元）",
          key: "debt_secured_amount",
          valueType: "amount",
        },
        { name: "状态", key: "status", valueType: "status" },
      ],
      // 商标
      intangible_sb: [
        { name: "申请人", key: "applicant_cn" },
        { name: "状态", key: "flow_status_desc", valueType: "status" },
        { name: "申请时间", key: "app_date" },
      ],
      // 专利
      intangible_zl: [
        { name: "申请人", key: "assignee_list" },
        { name: "状态", key: "legal_status_desc", valueType: "status" },
        { name: "申请时间", key: "app_date" },
        { name: "公开（公告）号", key: "publicationNumber" },
      ],
      // 排污权
      intangible_pwq: [
        { name: "行业类别", key: "industry_name" },
        { name: "许可证编号", key: "certificate_no" },
        { name: "状态", key: "state", valueType: "status" },
      ],
      // 招投标
      business_deal_ztb: [
        { name: "项目名称", key: "doc_title" },
        { name: "招投标类型", key: "tender_type" },
      ],
      // 移除失信执行/限制高消费
      other_yx: [
        { name: "案号", key: "ah" },
        { name: "立案时间", key: "larq" },
        { name: "案号", key: "casenumber" },
        { name: "限消令对象", key: "peopleenforced" },
        { name: "立案时间", key: "filingtime" },
      ],
    },
  },
  gotoDetail(e: any) {
    const info = e.currentTarget.dataset.info;
    const infoStr = JSON.stringify(info);

    if (info.subType === "sx_dw") {
      //债权人代位权
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/obligeeSubrogation/index?info=${infoStr}`,
      });
    } else if (info.subType === "sx_wja") {
      //司法涉诉未结案
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/JudicialLitigation/index?info=${infoStr}`,
      });
    } else if (info.subType === "stock_zq") {
      //股权质权
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/equityPledge/index?info=${infoStr}`,
      });
    } else if (info.subType === "stock_zy") {
      //股权质押
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/pledgeClues/index?info=${infoStr}`,
      });
    } else if (info.subType === "stock_zgs") {
      //债务人子公司
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/debtCompany/index?info=${infoStr}`,
      });
    } else if (info.subType === "stock_wsj") {
      //股东未实缴
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/holdersNoPay/index?info=${infoStr}`,
      });
    } else if (info.subType === "stock_yrz") {
      //一人制
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/onePerson/index?info=${infoStr}`,
      });
    } else if (info.subType === "real_td") {
      //土地抵押权
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/landRight/index?info=${infoStr}`,
      });
    } else if (info.subType === "real_js") {
      //土地抵押
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/landMortgage/index?info=${infoStr}`,
      });
    } else if (info.subType === "real_pm") {
      //土地拍卖
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/landAuction/index?info=${infoStr}`,
      });
    } else if (info.subType === "property_dy") {
      //动产质押/抵押
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/chattelPledge/index?info=${infoStr}`,
      });
    } else if (info.subType === "intangible_sb") {
      //商标
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/brand/index?info=${infoStr}`,
      });
    } else if (info.subType === "intangible_zl") {
      //专利
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/patent/index?info=${infoStr}`,
      });
    } else if (info.subType === "intangible_pwq") {
      //排污权
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/emissionRights/index?info=${infoStr}`,
      });
    } else if (info.subType === "business_deal_ztb") {
      //招投标
      wx.navigateTo({
        url: `/subPackages/packageA/propertyDetail/tendering/index?info=${infoStr}`,
      });
    }
  },
  // 更新时间筛选
  utimeSelect() {
    if (this.data.cur.idName === "utimeSelectorId" && this.data.visible) {
      this.setData({
        visible: false,
      });
      return;
    }
    this.setData(
      {
        cur: {
          idName: "utimeSelectorId",
          options: this.data.utimeOptions,
          defaultValue: this.data.utimeValue,
          multiple: false,
        },
      },
      () => {
        this.setData({
          visible: true,
        });
      }
    );
  },
  selectorChange(e: any) {
    // console.log(this.data.ptypeOptions, "ptypeOptions")
    // console.log(e.detail,"e.detail")
    let id = e.currentTarget.dataset.id;
    if (id === "ptypeSelectorId") {
      //类型选择
      let ptypeValue = e.detail.map((item: any) => item.value);
      this.setData(
        {
          ptype: e.detail,
          ptypeValue: ptypeValue,
          ptypeEnsureFlag: true,
        },
        () => {
          this.setSwiperPages();
          this.setPtypeOptions();
        }
      );
    }
    if (id === "utimeSelectorId") {
      // 时间筛选
      this.setData({
        utime: e.detail,
        utimeValue: [e.detail.value],
      });
      this.getTypeList();
    }
    if (id === "searchCInputId") {
      // 企业搜索筛选
      this.setData({
        companyId: e.detail.value,
        companyName: e.detail.label,
        keyWords: e.detail.label,
      });
      this.getTypeList();
    }
    // 更新线索列表
    this.getList("reset");
  },
  // 更新 ptypeOptions
  setPtypeOptions() {
    let ptypeOptions = this.data.ptypeOptions;
    let ptypeValue = this.data.ptypeValue;
    ptypeOptions.forEach((item, index) => {
      let key = `ptypeOptions[${index}].checked`;
      if (ptypeValue.indexOf(item.type) < 0) {
        this.setData({
          [key]: false,
        });
      } else {
        this.setData({
          [key]: true,
        });
      }
    });
  },
  // 线索类型筛选
  typeSelect() {
    if (this.data.cur.idName === "ptypeSelectorId" && this.data.visible) {
      this.setData({
        visible: false,
      });
      return;
    }
    this.setData(
      {
        cur: {
          idName: "ptypeSelectorId",
          options: this.data.ptypeOptions,
          defaultValue: this.data.ptypeValue,
          multiple: true,
        },
      },
      () => {
        this.setData({
          visible: true,
        });
      }
    );
  },
  // 获取线索类型列表
  getTypeList() {
    this.setData({
      typeLoading: true,
    });
    let dateInfo = this.data.utime.value === "all" ? "" : this.data.utime.value;
    let para = {
      id: this.data.companyId || "",
      dateInfo: dateInfo,
    };
    getClueTypeListAPI(para).then((res: any) => {
      if (res.code === "000") {
        let totalNum = res.content.totalNum;
        let typeList = res.content.typeList;
        let ptypeValue = this.data.ptypeValue;
        let result: any[] = [];
        if (typeList && typeList.length > 0) {
          typeList.forEach((item: any) => {
            result.push(...item.typeList);
          });
        }
        result.filter((item) => {
          item.label = item.typeName;
          item.value = item.type;
          item.checked = ptypeValue.includes(item.type);
          return true;
        });
        result.unshift({
          num: res.content.totalNum,
          typeName: "全部线索类型",
          type: "all",
          label: "全部线索类型",
          value: "all",
          checked: ptypeValue.includes("all"),
        });
        let ptypeOptions = result.slice();
        this.data.typeItemTotal = ptypeOptions.length;
        // 如果 swiperPages 不是空数组，？？？？
        let resultList = []; // [ [swiper-item], [swiper-item], [swiper-item]]
        let len = result.length;
        let itemNum = 9; // 每个swipterItem 展示的类型数量
        let size = Math.ceil((len + 1) / itemNum);
        for (var i = 0; i < size; i++) {
          let index = i * itemNum;
          if (index + itemNum >= len) {
            resultList.push(result.slice(index));
          } else {
            resultList.push(result.slice(index, index + itemNum));
          }
        }
        // console.log(resultList, "resultList")
        this.setData({
          ptypeOptions: ptypeOptions,
          swiperPages: resultList,
          totalNum: totalNum,
        });
        this.setData({
          typeLoading: false,
        });
      }
    });
  },
  // 点击线索对象名称，跳转企业详情
  gotoCompanyDetail(e: any) {
    const { id, companyname } = e.currentTarget.dataset;
    if (!id) return;
    wx.navigateTo({
      url:
        "/subPackages/packageA/debotrDetail/debtorDetail?debtorId=" +
        id +
        "&companyName=" +
        companyname,
    });
  },
  // 更新swiperPages
  setSwiperPages() {
    let swiperPages = this.data.swiperPages;
    let ptypeValue = this.data.ptypeValue;
    // let isTotal = ptypeValue.length === this.data.typeItemTotal;
    // 如果 线索类型下拉框 全部不勾选的情况？？？？
    swiperPages.forEach((itemList, i) => {
      itemList.forEach((item, j) => {
        let index = ptypeValue.indexOf(item.type);
        let key = `swiperPages[${i}][${j}].checked`;
        if (index < 0) {
          this.setData({
            [key]: false,
          });
        } else {
          this.setData({
            [key]: true,
          });
        }
      });
    });
  },
  // 点击类型分布图标
  typeItemClick(e: any) {
    if (this.data.listLoading) {
      return;
    }
    let type = e.currentTarget.dataset.type;
    // let num = e.currentTarget.dataset.num;
    // if (num == "0") {
    //   return;
    // }
    let ptypeValue = this.data.ptypeValue.slice();
    let index = ptypeValue.indexOf(type);
    let isAll = this.data.swiperPages[0][0].checked; //是否已经选择了全部
    if (type === "all") {
      // 点击 全部线索类型
      if (!isAll) {
        ptypeValue = ["all"];
      }
    } else {
      if (isAll) {
        // 点击选中，并且取消全部
        ptypeValue = [type];
      } else {
        if (index < 0) {
          // 点击选中
          ptypeValue.push(type);
        } else {
          ptypeValue.splice(index, 1);
          if (ptypeValue.length === 0) {
            ptypeValue.push("all");
          }
        }
      }
    }
    this.setData(
      {
        ptypeValue,
      },
      () => {
        // 更新 ptypeOptions
        this.setPtypeOptions();
        this.setSwiperPages();
        this.getList("reset");
      }
    );
  },
  // 获取全部企业列表
  getDebtorList() {
    reportGetDebtorListApi().then((res: any) => {
      if (res.code === "000") {
        let content = res.content || [];
        let options = content.map((item: any) => {
          return {
            label: item.name,
            value: item.value,
          };
        });
        this.setData({
          companyOptions: options,
        });
      }
    });
  },
  // 点击搜索
  searchFocus() {
    if (this.data.searchInputClass === "input-is-focus") return;
    this.setData(
      {
        searchInputClass: "input-is-focus",
        placeholderText: this.data.companyName || "请输入申请通过的企业名称",
        cur: {
          idName: "searchCInputId",
          options: this.data.companyOptions,
          defaultValue: [this.data.companyId],
          multiple: false,
        },
      },
      () => {
        this.setData({
          keyWords: "",
          visible: true,
          // searchDisabled: false,
        });
      }
    );
  },
  // 	聚焦时触发
  focusHandle() {
    if (this.data.searchInputClass && this.data.visible) return;
    this.setData({
      visible: true,
      placeholderText: this.data.companyName || "请输入申请通过的企业名称",
      keyWords: "",
      cur: {
        idName: "searchCInputId",
        options: this.data.companyOptions,
        defaultValue: [this.data.companyId],
        multiple: false,
      },
    });
  },
  // 收起
  searchBlur() {
    this.setData({
      searchInputClass: "",
      placeholderText: "搜索...",
      visible: false,
      keyWords: this.data.companyName,
      // searchDisabled: true,
    });
  },
  // 搜索框输入关键字
  searchChange() {},
  // 清除企业搜索 不包括时间和线索类型筛选清除
  clearHandle() {
    if (this.data.companyName && this.data.companyId) {
      this.setData({
        companyId: null,
        companyName: "",
        keyWords: "",
        placeholderText: "搜索...",
        searchInputClass: "",
        visible: false,
        cur: {
          defaultValue: [],
          options: [],
          idName: "",
        },
      });
      this.getTypeList();
      this.getList("reset");
    } else {
      this.setData({
        keyWords: "",
        placeholderText: "搜索...",
        searchInputClass: "",
        visible: false,
        // searchDisabled: true,
        cur: {
          defaultValue: [],
          options: [],
          idName: "",
        },
      });
    }
  },
  // 获取财产线索列表
  getList(oper?: string) {
    if (oper && oper === "reset") {
      this.data.page = 1;
      this.data.hasNextPage = true;
      // this.setData({
      //   clueStatList: []
      // })
      this.data.clueStatList = [];
    }
    let subTypes = this.data.ptypeValue.includes("all")
      ? ""
      : this.data.ptypeValue.join(",");
    let dateInfo = this.data.utime.value === "all" ? "" : this.data.utime.value;
    let para = {
      page: this.data.page,
      perPage: this.data.perPage,
      id: this.data.companyId || "",
      subTypes: subTypes,
      dateInfo: dateInfo,
    };
    this.setData({
      listLoading: true,
    });
    getClueStatListAPI(para).then((res) => {
      if (res.code === "000") {
        let contentList = res.content.list || [];
        this.data.hasNextPage = res.content.hasNextPage;
        let clueStatList = this.data.clueStatList.slice();
        this.setData(
          {
            clueStatList: clueStatList.concat(contentList),
            total: res.content.total,
          },
          () => {
            this.setData({
              listLoading: false,
            });
          }
        );
      }
    });
    // 获取预估价值
    getClueStatAmountAPI(para).then((res: any) => {
      if (res.code === "000") {
        this.setData({
          totalAmount: debtorPrice(res.content),
        });
      }
    });
  },
  // 滚到到底 加载列表
  scrollToLowerHandle() {
    if (this.data.hasNextPage) {
      this.data.page = this.data.page + 1;
      this.getList();
    }
  },
  // 点击标题栏回到顶部
  // enable-back-to-top：iOS点击顶部状态栏、安卓双击标题栏时，滚动条返回顶部，只支持竖向，且当自定义标题栏后就会失效
  backToTopHandle() {
    this.setData({
      scrollTop: 0,
    });
  },
  // 设置搜索的企业
  setCompany() {
    let app = getApp();
    let companyPara = app.globalData.companyPara;
    if (companyPara && companyPara.debtorId) {
      console.log(companyPara, "companyPara");
      this.setData({
        companyId: companyPara.debtorId,
        companyName: companyPara.companyName,
        keyWords: companyPara.companyName,
        searchInputClass: "input-is-focus",
        // searchDisabled: false
      });
      console.log("重新搜索");
      this.searchParaReset();
      this.getTypeList();
      this.getList("reset");
    }
  },
  // 清除 搜索的企业全局数据
  clearCompany() {
    let app = getApp();
    app.globalData.companyPara = {
      companyId: null,
      companyName: "",
    };
  },
  // 清除页面搜索参数
  searchParaReset() {
    this.data.page = 1;
    this.data.hasNextPage = true;
    this.setData({
      total: 0,
      scrollTop: 0,
      utime: { value: "", label: "" },
      utimeValue: ["all"],
      ptype: [],
      ptypeValue: ["all"],
      clueStatList: [],
    });
  },
  // 页面初始化
  init() {
    this.setData({
      companyId: null,
      companyName: "",
      keyWords: "",
      searchInputClass: "",
      placeholderText: "搜索...",
      visible: false,
      // searchDisabled: true,
    });
    this.searchParaReset();
  },
  // 监听
  // observers: {
  //   "debtorId": function (){
  //     console.log("debtorId change!!!")

  //   }
  // },
  // getTabBar 回调设置自定义tab-bar 高亮
  getInstance() {
    if (typeof this.getTabBar === "function") {
      const tabBar = this.getTabBar();
      tabBar.setData({
        // active: 2
        // hide shiye
        active: 3,
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 如果onLoad 没有触发之前，从债务人详情跳转至财产线索页面，查询当前债务人的财产线索
    let app = getApp();
    let companyPara = app.globalData.companyPara;
    app.globalData.prevPage = "";
    if (!companyPara.debtorId) {
      this.getTypeList();
      this.getList("reset");
    }
    this.getDebtorList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getInstance();
    const prevPage = getApp().globalData.prevPage;
    if (prevPage === "mine" || prevPage === "index") {
      // 由 我的 页面点击跳转, 首页点击跳转
      // 刷新页面
      this.init();
      this.getTypeList();
      this.getList("reset");
      this.getDebtorList();
    } else {
      let app = getApp();
      let companyPara = app.globalData.companyPara;
      if (companyPara.debtorId) {
        this.setCompany();
      }
      this.getDebtorList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.clearCompany();
    getApp().globalData.prevPage = "";
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.clearCompany();
    getApp().globalData.prevPage = "";
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
});
